import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { createJwtToken } from '@/lib/auth/jwt';

const registerSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
  password: z.string().min(6),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const validatedData = registerSchema.parse(body);

    // 在实际应用中，您应该将用户数据保存到数据库
    // 这里我们只是模拟注册成功并返回一个 token

    // 模拟创建新用户
    const newUser = {
      id: `user_${Date.now()}`,
      email: validatedData.email,
      name: validatedData.name,
      role: 'user',
    };

    // 创建 JWT token
    const token = await createJwtToken({
      sub: newUser.id,
      email: newUser.email,
      name: newUser.name,
      role: newUser.role,
    });

    // 返回用户信息和 token
    return NextResponse.json({
      success: true,
      message: '注册成功',
      status: 201,
      data: {
        user: newUser,
        token,
      }
    });
  } catch (error) {
    console.error('注册错误', error);
    
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { success: false, message: '无效的请求数据', errors: error.flatten().fieldErrors },
        { status: 400 }
      );
    }
    
    return NextResponse.json(
      { success: false, message: '注册失败，请稍后再试' },
      { status: 500 }
    );
  }
} 